﻿package org.cshoo.sys.business.service;

import java.util.ArrayList;
import java.util.List;

import org.cshoo.sys.business.iservice.IUserService;
import org.cshoo.sys.data.entity.User;
import org.cshoo.sys.data.idao.IAuthorityDAO;
import org.cshoo.sys.data.idao.IMenuDAO;
import org.cshoo.sys.data.idao.IUserDAO;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.support.WebApplicationContextUtils;

import flex.messaging.FlexContext;

/**
 * 用户管理后台业务处理类
 * @author 杨翼
 * 2012年10月7日 杨翼 创建
 */
public class UserService implements IUserService{
	
	private IUserDAO userDAO;
	private IMenuDAO menuDAO;
	private IAuthorityDAO authorityDAO;
	
	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	public void setMenuDAO(IMenuDAO menuDAO){
		this.menuDAO = menuDAO;
	}
	
	
	public void setAuthorityDAO(IAuthorityDAO authorityDAO) {
		this.authorityDAO = authorityDAO;
	}

	/**
	 * 用户登录
	 * @param userExample 填写成的用户实例，只包括用户名密码信息，其他信息为null
	 * @return 登录结构
	 */
	public List login(User userExample){
		List result = new ArrayList();
			
        ApplicationContext appContext =
                WebApplicationContextUtils.getWebApplicationContext(FlexContext.getServletConfig().getServletContext());
        AuthenticationManager manager = (AuthenticationManager)appContext.getBean("authenticationManager");
        
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(userExample.getUserName(),userExample.getPassword());
        try
        {
        	Authentication authentication = manager.authenticate(usernamePasswordAuthenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            //1、取到登录成功的user对象，并放入结果列表中
            userExample.setPassword(null);
            User currentUser = (User)(userDAO.findObjectListByExample(userExample).get(0));
            result.add(currentUser);
            
//            //2、取到当前登录成功的user对象的菜单，这里大概用到的方法如下：第一步，先取到所有的根菜单（由于菜单递归，所以相当于取到了所有菜单）；第二步，对每个根菜单过滤其中没有权限的菜单；
//    		//第一步，取到所有根菜单；
//            List rootMenuList = menuDAO.findRootMenuList();
//            
//    		//第二步，取出权限列表
//    		List authorityList = new ArrayList();
//    		//①遍历此用户角色，取出当前用户的角色菜单权限列表，并入权限列表中；
//    		for(Role role:currentUser.getRoleSet())
//    		{
//    			Authority authorityExample = new Authority();
//    			authorityExample.setType("角色菜单权限");
//    			authorityExample.setRole(role);
//    			authorityList.addAll(authorityDAO.findObjectListByExample(authorityExample));
//    		}
//    		//②取出用户菜单权限，放入权限列表中；
//    		Authority authorityExample = new Authority();
//    		authorityExample.setType("用户菜单权限");
//    		authorityExample.setUser(currentUser);
//    		authorityList.addAll(authorityDAO.findObjectListByExample(authorityExample));
//    		
//    		//第三步，过滤根菜单列表，把过滤后的列表加入result中
//    		List menuList = FilterMenuTree.filterMenuList(rootMenuList, authorityList);
//    		result.add(menuList);
        }
        catch(BadCredentialsException e){
        }
		return result;
	}
	
	/**
	 * 退出
	 * @return
	 */
	public Boolean logout(){
		Boolean result = false;
		SecurityContextHolder.clearContext();
		result = true;
		return result;
	}
	
	/**
	 * 添加一个用户,
	 * 在这里密码进行了sha加密，盐值设置为username
	 * @param user
	 * @return
	 */
	public Boolean addUser(User user){
		Boolean result = false;
		ShaPasswordEncoder shaPasswordEncoder = new ShaPasswordEncoder(); 
		user.setPassword(shaPasswordEncoder.encodePassword(user.getPassword(), user.getUserName()));
		userDAO.addObject(user);
		result = true;
		return result;
	}
	
	/**
	 * 修改用户信息
	 * @param user
	 * @return
	 */
	public Boolean updateUser(User user){
		Boolean result = false;
		userDAO.updateObject(user);
		result = true;
		return result;
	}
	
	/**
	 * 查询符合条件的用户
	 * @param userExample
	 * @return
	 */
	public List findUserList(User userExample){
		return userDAO.findObjectListByExample(userExample);
	}
}
